import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/user/user.entity';
import { Repository } from 'typeorm';
import { RegisterDto } from './dto/register.dto';

import { hashSync } from 'bcryptjs'
import { compareSync } from 'bcryptjs'

@Injectable()
export class AuthService {
    constructor(
        @InjectRepository(User)
        private readonly userRepo: Repository<User>,
    ){}

    // 注册用户
    async regisUser(newUser: RegisterDto){
        const addedUser = new User()
        addedUser.nickName = newUser.nickName
        addedUser.username = newUser.username
        addedUser.password = newUser.password ? hashSync(newUser.password) : newUser.password
        addedUser.email = newUser.email
        addedUser.avatar = newUser.avatar
        addedUser.type = newUser.type
        addedUser.description = newUser.description
        return await this.userRepo.save(addedUser)
    }

    // 验证用户
    async validateUser(username: string, password: string){
        const user = await this.userRepo.findOne({username: username})
        if(user && compareSync(password, user.password)){
            return user
        }
        return null
    }

    // 根据获取用户
    async findUserById(id: string){
        return await this.userRepo.findOne(id)
    }
}
